package controller;

import bean.Pest;
import com.google.gson.Gson;
import service.IPestService;
import service.Impl.PestServiceImpl;
import util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "PestServlet",urlPatterns = "/pest.do")
public class PestServlet extends HttpServlet {

    IPestService ips =new PestServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String method = request.getParameter("method");
        if(method==null||method.equals("")){
//            System.out.println("根本没有进入添加流程");
            ListByPage(request,response);
        }else if(method.equals("addPest")){
//            System.out.println("执行打印了吗？----");
            addPest(request,response);
        }
    }
    protected void ListByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNo1 = request.getParameter("pageNo");
        String pageSize1 = request.getParameter("pageSize");
        int pageNo =1;
        int pageSize =10;
        if(pageNo1==null||pageNo1.equals("")){

        }else{
             pageNo =Integer.parseInt(pageNo1) ;
             pageSize =Integer.parseInt(pageSize1 );
        }

        String f_pestName = request.getParameter("f_pestName");
        String f_host = request.getParameter("f_host");
        PageUtil<Pest> pages=null;
        if(f_pestName==null&&f_host==null){
            pages= ips.ListByPage(pageNo, pageSize);
        }
        else if(f_pestName!=null||f_host!=null) {
            pages= ips.ListByPage(pageNo, pageSize,f_pestName,f_host);
        }
        Gson gson =new Gson();
        String json = gson.toJson(pages);
        PrintWriter out = response.getWriter();
        out.write(json);

    }
    protected void addPest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Pest p =new Pest();
        String f_pestName = request.getParameter("f_pestName");
        String f_host = request.getParameter("f_host");
        String f_detriment = request.getParameter("f_detriment");
        p.setF_pestName(f_pestName);
        p.setF_host(f_host);
        p.setF_detriment(f_detriment);
        boolean b = ips.addPest(p);
        if(b){
            response.sendRedirect("/pestSystem/home/pestData.html");
        }else{
            System.out.println("添加失败.......  ");
        }

    }
}
